# -*- coding: utf-8 -*-

from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib import messages
from django.core.urlresolvers import reverse

from codeshare.main.models import *
from codeshare.main.forms import CodeSubmitForm
def index(request):
    """Index view.
        Displays the 10 most recent/popular/highest rated code submissions."""
    
    codes = Code.objects.all().order_by("-created", "views", "average")[:10]
    
    return render_to_response("index.html", RequestContext(request, {
        'codes':codes
    }))
def view_code(request, pid, cid):
    """Allows the user to view a code snippet from a given project."""
    pass
def create_project(request, pid):
    pass
def submit_code(request):
    """Main view for submitting code.
        Mainly just displays the form and processes it."""
    
    if request.method == "GET":
        form = CodeSubmitForm()
    else:
        form = CodeSubmitForm(request.POST)
        
        if form.is_valid():
            #Valid form; save it
            d = form.cleaned_data
            code = Code.objects.create(
                title=d['title'],
                description=d['description'],
                language=d['language'],
                code=d['code'],
                author=request.user
            )
            code.save()
            
            #And that's all folks!
            messages.success(request, "Your code has been submitted!")
            
            return HttpResponseRedirect(reverse("main:view_code", args=[code.pk]))
    
    return render_to_response("submit_code.html", RequestContext(request, {
        'form':form
    }))